from flask import abort, jsonify
from flask import current_app
from flask import g
from flask import render_template
from flask import request

from info.utils.common import user_login_data
from info import constants, db
from info.models import User, News, Comment, CommentLike
from info.modules.news import news_blu
from info.utils.response_code import RET


@news_blu.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    # 获取当前登陆用户的id
    # user_id = session.get("user_id")
    # # 通过用户id获取用户信息
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger(e)
    user = g.user   # 通过g变量接收登陆用户的id参数
    # 新闻前台 点击排行
    # news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger(e)

    click_news_list = []
    for news in news_list:
        click_news_list.append(news.to_dict())


    # 查询新闻数据
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)
        # return jsonify(errno=RET.NODATA,errmsg='没有此新闻')

        # News.query.get(news_id) 有可能返回 空
    if news is None:
        abort(404)
    news.clicks += 1

    # 1 收藏功能 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    is_followed = False
    is_collected = False
    if user:
        if news in user.collection_news:
            is_collected = True
        try:
            news_user = User.query.get(news.user_id)
        except Exception as e:
            return jsonify(errno=RET.DBERR, errmsg='查询失败')
        # 如果新闻作者是登录用户的粉丝 就是关注的用户
        if news_user in user.followers:
            is_followed = True

    # 当前新闻的评论  xxxxxxxxxxxxxxxxxxxxxxx
    comments = None
    try:
        comments = Comment.query.filter(Comment.news_id==news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)

    # 点赞功能
    comment_like_ids = []
    if user:
        try:
            comment_ids = [comment.id for comment in comments]
            if len(comment_ids)>0:
                # 查询当前新闻所有评论点赞的记录
                comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),
                                                         CommentLike.user_id == user.id).all()
                # 取出记录所有评论的id
                comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]
        except Exception as e:
            current_app.logger.error(e)

    comments_list = []
    for item in comments if comments else []:
        comments_dict=item.to_dict()
        comments_dict["is_like"] = False
        if user and item.id in comment_like_ids:
            comments_dict["is_like"] = True
        comments_list.append(comments_dict)

    data={
        "user": user.to_dict() if user else None,
        "click_news_list": click_news_list,
        "news":news.to_dict(),
        "is_collected":is_collected,
        "comments":comments_list,
        "is_followed":is_followed
    }
    return render_template('news/detail.html', data=data)
# 新闻收藏功能
@news_blu.route('/news_collect', methods=['POST'])
@user_login_data
def news_collect():
    user = g.user
    news_id = request.json.get('news_id')
    action = request.json.get('action')

    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='用户未登录')

    if not news_id:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if action not in ("collect", "cancel_collect"):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据失败')

    if not news:
        return jsonify(errno=RET.NODATA, errmsg='新闻数据不存在')

    if action == "collect":
        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存失败')
    return jsonify(errno=RET.OK, errmsg='操作成功')
"""
评论的需求： 1.必须是登陆用户  要传递 新闻的id 评论内容

1. 这个试图必须是登陆用户才可以访问
2. 要接收参数， news_id, content
3. 2个参数必须有，
4. 判断 news 必须存在
5. 数据入库
6. 返回响应 同时把 新增的数据传递给前端
"""
# 新闻评论功能
@news_blu.route('/news_comment', methods=['POST'])
@user_login_data
def add_news_comment():
    # 1 必须是登陆用户  要传递 新闻的id 评论内容
    user = g.user
    if not user:
        return jsonify(errno=RET.DBERR, errmsg='用户未登陆')
    # 2 接收参数
    news_id = request.json.get('news_id')
    content = request.json.get('comment')
    parent_comment_id = request.json.get('parent_id')
    # 3 2个参数必须有
    if not all([news_id, content]):
        return jsonify(errno=RET.DBERR, errmsg='参数不全')
    # 4 判断 news 必须存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询失败')
    if not news:
        return jsonify(errno=RET.NODATA, errmsg='未查询到该新闻')
    # 5 数据入库
    comment = Comment()
    comment.user_id=user.id
    comment.news_id=news_id
    comment.content=content
    # 跟帖回复功能
    if parent_comment_id:
        comment.parent_id=parent_comment_id

    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()

    # 6 返回响应 同时把 新增的数据传递给前端
    return jsonify(errno=RET.OK, errmsg='ok',
                   data={"comment":comment.to_dict()})

"""
点赞的需求：
    需要将 用户信息， 评论的id 传递给后端 点赞的状态 传递给后端

1. 点赞功能必须要登陆
2. 接收参数 ，并且对参数进行判断
3. comment_id 进行查询，并且判断 必须有评论
4. 数据入库
5. 返回相应
"""
# 点赞功能
@news_blu.route('/comment_like', methods=['POST'])
@user_login_data
def comment_like():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登陆')

    # 2 接收参数
    comment_id = request.json.get('comment_id')
    action = request.json.get('action')
    if not all([comment_id, action]):
        return jsonify(errno=RET.DBERR, errmsg='参数错误')
    if action not in ['add', 'remove']:
        return jsonify(errno=RET.DBERR, errmsg='action问题')

    # 3 comment_id 进行查询，并且判断 必须有评论
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询失败')
    if not comment:
        return jsonify(errno=RET.DBERR, errmsg='没有评论')

    # 4. 数据入库 查询此评论的id和此用户是否点赞
    if action == 'add':
        comment_like = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                CommentLike.user_id == user.id).first()
        if not comment_like:
            # 没有点赞 则添加到数据库
            cl = CommentLike()
            cl.comment_id=comment_id
            cl.user_id=user.id
            comment.like_count += 1
            try:
                db.session.add(cl)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                db.session.rollback()
    else:
        comment_like = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                CommentLike.user_id == user.id).first()
        if comment_like:
            # 有点赞 则删除数据库
            comment.like_count -= 1
            try:
                db.session.add(comment_like)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                db.session.rollback()
    return jsonify(errno=RET.OK, errmsg='ok')
# 关注/取消关注用户
@news_blu.route('/followed_user', methods=["POST"])
@user_login_data
def followed_user():
    """关注/取消关注用户"""
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登陆')

    # 接收参数
    user_id = request.json.get("user_id")
    action = request.json.get("action")
    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    if action not in ("follow", "unfollow"):
        return jsonify(errno=RET.PARAMERR, errmsg='用参数action错误')
    # 查询关注的用户信息
    try:
        news_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据库失败')

    if not news_user:
        return jsonify(errno=RET.DBERR, errmsg='未找到用户数据')

    # 业务逻辑判断
    if action == "follow":
        if news_user not in user.followers:
            user.followers.append(news_user)
    else:
        if news_user in user.followers:
            user.followers.remove(news_user)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()

    return jsonify(errno=RET.OK, errmsg='OK')




















